/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.order.so.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.so.dao.model.SoHead;
import com.erp.order.so.dao.model.SoLine;
import com.erp.order.so.dao.model.SoLineBase;
import com.erp.order.so.dao.model.SoLineCO;
import com.erp.order.so.service.SoLineService;
import com.erp.order.soa.dao.model.SoAgreementLine;
import com.erp.order.soa.dao.model.SoAgreementLineCO;
import com.erp.order.soa.service.SoAgreementHeadService;
import com.erp.order.soa.service.SoAgreementLineService;
import com.erp.order.soeco.dao.model.SoLineM;
import com.erp.order.soeco.service.SoEcoService;
import com.erp.order.soeco.service.SoLineMService;

@Controller
@RequestMapping("/web/soLine")
public class SoLineWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(SoLineWebController.class);
    
    //服务层注入
    @Autowired
    private SoLineService soLineService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private SoLineMService soLineMService;
    @Autowired
    private SoAgreementHeadService soAgreementHeadService;
    @Autowired
    private SoAgreementLineService soAgreementLineService;
    @Autowired
    private SoEcoService soEcoService;
    
    
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getSoLineList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-07-17 20:16:18
     * @author 
     * @param pages
     * @param soLineCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getSoLineList")
    public String getSoLineList(Pages pages, SoLineCO soLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //分页查询数据
        List<SoLineBase> soLineList = new ArrayList<SoLineBase>();
        //根据version请求参数，判断数据从原表获取还是变更表获取
        if(soLineCO.getVersion()!=null&&soLineCO.getVersion()>0) {
            SoLineM soLineM = new SoLineM();
            soLineM.setSoHeadCode(soLineCO.getSoHeadCode());
            soLineM.setVersion(soLineCO.getVersion());
            List<SoLineM> list = this.soLineMService.getDataObjects(pages, soLineM);
            for(SoLineM obj: list) {
                soLineList.add(obj);
            }
        }else {
            List<SoLine> list = this.soLineService.getSoLineListBySoHeadCode(pages, soLineCO);
            for(SoLine obj: list) {
                soLineList.add(obj);
            }
        }
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("soLineList", soLineList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        
        return "so/tab/soLineTab";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-07-17 20:16:18
     * @author 
     * @param soLine
     * @param model
     * @return String
     *
     */
    @RequestMapping("getSoLine")
    public String getSoLine(SoLine soLine, SoHead soHead, Model model) {
        //查询要编辑的数据
        Integer soLineIdSearch = 0;
        if(soLine!=null&&soLine.getSoLineId()!=null) {
            soLine = this.soLineService.getDataObject(soLine.getSoLineId());
            soLineIdSearch = soLine.getSoLineId();
        }else {
            soLine.setAmount(BigDecimal.ZERO);
        }
        
        //订单行的协议验证行
        Map<String, SoAgreementLine> soaLineMap = new HashMap<String, SoAgreementLine>();
        
        //如果是协议订单获取协议内容
        if(soHead!=null&&StringUtils.isNotBlank(soHead.getSoAgreementHeadCode())) {
            //获取协议头
            //PoAgreementHead poAgreementHead = this.poAgreementHeadService.getDataObject(poHead.getPoAgreementHeadCode());
            
            //获取协议行
            Pages pages = new Pages();
            pages.setPage(1);
            pages.setMax(100);
            SoAgreementLineCO soAgreementLineCO = new SoAgreementLineCO();
            soAgreementLineCO.setSoHeadCode(soHead.getSoAgreementHeadCode());
            List<SoAgreementLine> soAgreementLineList = this.soAgreementLineService.getSoLineListBySoHeadCode(pages, soAgreementLineCO);
            //设置订单行的协议验证行
            for(int a=0;a<soAgreementLineList.size();a++) {
                //获取协议已完成行数量,协议有数量限制才会计算发放数量
                if(soAgreementLineList.get(a).getQuantity()!=null) {
                    Double agreementFinishQuantity = this.soEcoService.getSoLineQuantityByAgreement(soAgreementLineList.get(a).getSoHeadCode(), soAgreementLineList.get(a).getMaterialCode(), soLineIdSearch);
                    soAgreementLineList.get(a).setAgreementFinishQuantity(agreementFinishQuantity);
                }
                
                //循环设置协议行map
                soaLineMap.put(soAgreementLineList.get(a).getMaterialCode(), soAgreementLineList.get(a));
            }
        }
        
        //物料
        Map<String, String> materialMap = this.masterDataCommonService.getMaterialMap();
        Map<String, String> materialLineMap = new HashMap<String, String>();
        //如果存在协议行则限定订单行的物料范围
        if(soaLineMap.size()>0) {
            for(String key: soaLineMap.keySet()) {
                materialLineMap.put(key, materialMap.get(key));
            }
        }else {
            materialLineMap.putAll(materialMap);
        }
        //去除订单行已存在的物料
        Pages pages = new Pages();
        pages.setPage(1);
        pages.setMax(100);
        SoLineCO soLineCO = new SoLineCO();
        soLineCO.setSoHeadCode(soLine.getSoHeadCode());
        //获取订单行
        List<SoLine> soLineList = this.soLineService.getSoLineListBySoHeadCode(pages, soLineCO);
        //循环删除已存在的物料
        for(SoLine soLineTemp: soLineList) {
            if(soLine!=null&&soLine.getSoLineId()!=null) {
                if(soLine.getSoLineId()!=soLineTemp.getSoLineId()) {
                    materialLineMap.remove(soLineTemp.getMaterialCode());
                }
            }else {
                materialLineMap.remove(soLineTemp.getMaterialCode());
            }
        }
        
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("soLine", soLine);
        model.addAttribute("materialMap", materialLineMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("soaLineMap", soaLineMap);
        
        return "so/pop/addLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-07-17 20:16:18
     * @author 
     * @param soLine
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editSoLine")
    @ResponseBody
    public String editSoLine(@Valid @RequestBody SoLine soLine, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            /*
            //参数校验
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getSoLine";
            }
            */
            
            //对当前编辑的对象初始化默认的字段
            if(soLine.getSoLineId()==null) {
                soLine.setSoLineCode(SnowFlake.getConcurrentId().toString());
            }
            
            //保存编辑的数据
            this.soLineService.insertOrUpdateDataObject(soLine);
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-07-17 20:16:18
     * @author 
     * @param soLine
     * @return String
     *
     */
    @RequestMapping("deleteSoLine")
    @ResponseBody
    public String deleteSoLine(@RequestBody SoLine soLine, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(soLine!=null&&soLine.getSoLineId()!=null) {
                //删除数据
                this.soLineService.deleteDataObject(soLine);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
}
